package top.jiangqiang.qyblog.common.handler;

import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@Component
@Slf4j
public class TypeConverter {

    private final ConversionService conversionService;

    public TypeConverter(@Lazy ConversionService conversionService) {
        this.conversionService = conversionService;
    }

    /**
     * 对象类型转换
     *
     * @param source    源对象
     * @param distClass 目标类型
     * @return 目标类型的对象
     */
    public <S, D> D convert(@NotNull S source, @NotNull Class<D> distClass) {
        try {
            return conversionService.convert(source, distClass);
        } catch (Exception e) {
            log.warn(e.getMessage());
            log.warn("没有对应的mapstruct转换器:{}=>{}，使用BeanUtil进行转换", source.getClass().getSimpleName(), distClass.getSimpleName());
            return BeanUtil.copyProperties(source, distClass);
        }
    }

    /**
     * 转换集合类型
     *
     * @return
     */
    public <S, D> List<D> convertList(@NotNull Collection<S> sourceCollection, @NotNull Class<D> clazz) {
        return sourceCollection.stream().map(item -> convert(item, clazz)).toList();
    }

    public <S, D> List<D> convertList(@NotNull S[] sourceArray, @NotNull Class<D> clazz) {
        return Arrays.stream(sourceArray).map(item -> convert(item, clazz)).toList();
    }

}
